package com.xsq.newmall01.ServiceImpl.UserServiceImpl;

import com.xsq.newmall01.Dao.Order;
import com.xsq.newmall01.Dao.Ownership;
import com.xsq.newmall01.Dao.User;
import com.xsq.newmall01.Mapper.UserMapper;
import com.xsq.newmall01.Service.UserService.UOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service("userorderservice")
public class UOrderServiceImpl implements UOrderService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Order> getOwnedOrders(User user) {
        // 调用mapper查询用户的订单
        return userMapper.selectownedorder(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createOrder(Order order, Ownership ownership) {

        // 1. 查询商品原商家ID（userkind=2）
        int sellerId = userMapper.selectSellerIdByGoodId(ownership.getGoodid());
        if (sellerId <= 0) {
            throw new RuntimeException("商品不存在或不属于任何商家");
        }

        // 2. 设置订单的商家ID（senderid）
        order.setSenderid(sellerId);

        // 2. 设置订单的商家ID和下单时间（新增时间设置）
        order.setSenderid(sellerId);
        order.setCreatetime(new Date()); // 设置当前时间为下单时间

        // 1. 创建订单
        userMapper.insertorder(order);
        // 2. 更新商品所有权（从商家转移到买家）
        userMapper.updateownership(ownership);
    }
}
